// pages/productdivide/productdivide.js
const alioss = require('../../utils/alioss.js');
const {
  requestApi,
  wxrequest,
  wxdownload
} = require('../../utils/util.js');
const MAX_PIC_WIDTH = 2000;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    divided_url: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  navBack() {
    wx.navigateBack()
  },
  preview() {

  },
  chooseOne() {
    let this_ = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        let filePath = res.tempFiles[0].tempFilePath;
        console.log(filePath);
        this_.requestAli(filePath);
      },
      fail: (err) => {
        if (err.errMsg == 'chooseMedia:fail cancel') {
          return;
        }
        console.log(err)
        wx.showToast({
          title: '不支持的格式',
          icon: 'error',
          duration: 2000
        })
      }
    });
  },
  requestAli(filePath) {
    wx.showLoading({
      title: '图片上传中',
    })
    alioss.uploadFile(filePath, 'qiqi_tool/product_divide/').then(async res => {
      let imgUrl = res.data.url;
      let imgInfo = await wxrequest(imgUrl + '?x-oss-process=image/info', 'GET');
      console.log(imgInfo)
      let type = imgInfo.Format.value;
      let height = +imgInfo.ImageHeight.value;
      let width = +imgInfo.ImageWidth.value;
      let imgOssProcessOption = '';
      let transformat = false;
      if (type != 'jpeg' || type != 'png') {
        imgOssProcessOption = type == 'heic' ? 'format,png' : 'format,jpeg' + imgOssProcessOption;
        transformat = true;
      }
      if (height > MAX_PIC_WIDTH || width > MAX_PIC_WIDTH) {
        if (height > width) {
          imgOssProcessOption = 'resize,h_' + MAX_PIC_WIDTH + '/' + imgOssProcessOption
        } else {
          imgOssProcessOption = 'resize,w_' + MAX_PIC_WIDTH + '/' + imgOssProcessOption
        }
      }
      if (imgOssProcessOption != '') {
        imgOssProcessOption = '?x-oss-process=image/' + imgOssProcessOption
      }
      if (!transformat) {
        return Promise.resolve(imgUrl + imgOssProcessOption)
      } else {
        return wxdownload(imgUrl + imgOssProcessOption).then(res => {
          let tempFilePath = res.tempFilePath;
          return alioss.uploadFile(tempFilePath, 'qiqi_tool/product_divide/').then(res => {
            let imgUrl = res.data.url;
            return Promise.resolve(imgUrl);
          })
        })
      }
    }).then(fileUrl => {
      console.log(fileUrl)
      wx.hideLoading()
      wx.showLoading({
        title: '图片分割中',
      })
      return requestApi('productDivideApi', {
        ImageURL: fileUrl
      })
    }).then(res => {
      console.log(res);
      this.setData({
        divided_url: res.result.Data.ImageURL
      })
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: '系统异常',
        icon: 'error'
      })
      console.log(err);
    }).finally(() => {
      wx.hideLoading()
    })
  },
  download() {
    let this_ = this;
    let url = this_.data.divided_url;
    url = url.replace('http://', 'https://');
    wx.showLoading({
      title: '图片下载中',
    })
    wx.downloadFile({
      url: url,
      success: function (res) {
        var temp = res.tempFilePath
        wx.saveImageToPhotosAlbum({
          filePath: temp,
          success(res) {
            console.log(res)
            wx.showToast({
              title: '下载成功',
              icon: 'success'
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
      },
      fail: function (err) {
        this_.report('download_err', err);
        if (err.errno == '600002') {
          let msg = err.errMsg.split(':')[2];
          this_.report('download_domain', {
            errno: 600002,
            errMsg: msg,
            url: url
          });
        }
        console.log(err)
      },
      complete: function () {
        wx.hideLoading()
      }
    });
  },
  report(id, err) {
    wx.reportEvent(id, {
      "errno": err.errno,
      "msg": err.errMsg,
      "url": err.url
    })
  }
})